package com.example.gateway.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhouyp
 * @program gateway
 * @description
 * @create 2020-07-26
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {

	@Value("${iplimit.duration}")
	private Integer limitDuration;

	@Value("${iplimit.count}")
	private Integer limitCount;

	private static final Map<String, Long> ipAccessTimeMillisCache = new HashMap<>();

	private static final Map<String, AtomicInteger> ipAccessCountCache = new HashMap<>();

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		System.out.println("开始执行ipfilter");

		final ServerHttpRequest request = exchange.getRequest();
		final ServerHttpResponse response = exchange.getResponse();
		final String path = request.getURI().getPath();

		if (path.startsWith("/api/user/register")) {
			final InetSocketAddress clientAddr = request.getRemoteAddress();
			Objects.requireNonNull(clientAddr, "未获取到访问ip");
			final String clientIp = clientAddr.getHostString();

			if (ipAccessTimeMillisCache.containsKey(clientIp)) {
				final AtomicInteger realCount = ipAccessCountCache.get(clientIp);

				if (realCount.incrementAndGet() >= limitCount) {
					response.setStatusCode(HttpStatus.SEE_OTHER);
					String data = "您频繁进⾏注册，请求已被拒绝";
					System.out.println("IP:" + clientIp + data);
					DataBuffer wrap = response.bufferFactory()
							.wrap(data.getBytes(StandardCharsets.UTF_8));
					return response.writeWith(Mono.just(wrap));
				}

				final Long lastAccessTimeMillis = ipAccessTimeMillisCache.get(clientIp);
				final long nowTime = System.currentTimeMillis() / 1000;
				final long limitTime = nowTime - lastAccessTimeMillis;

				if (limitTime > limitDuration) {
					ipAccessCountCache.put(clientIp, new AtomicInteger(1));
					ipAccessTimeMillisCache.put(clientIp, (System.currentTimeMillis() / 1000));
				} else {
					ipAccessCountCache.put(clientIp, realCount);
				}
			} else {
				ipAccessTimeMillisCache.put(clientIp, (System.currentTimeMillis() / 1000));
				ipAccessCountCache.put(clientIp, new AtomicInteger(1));
			}
		}
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
